<?php
/**
 *
 * @author  Devret
 * @mail    461313128@qq.com
 * @create  2020-03-10 21:58
 * https://sixcloud.co/
 * https://gitee.com/devret/AuthorizationSystem.git
 */

header('Content-Type: text/html; charset=UTF-8');
define('ROOT', $_SERVER['DOCUMENT_ROOT'] . "/");
include(ROOT . "session.inc.php");
$type = $_GET['type'];
if (!isset($_GET['type'])) {
    die(OperateResult::out(false, "type参数不能为空", ""));
}
$UPDATE_URL = 'http://version.916b.cn/update.php?version='.SYSTEM_VERSION;
switch ($type) {
    case 'check':
        check($UPDATE_URL);
        break;
    case 'update':
        update($UPDATE_URL);
        break;
}


function getMillisecond() {

    list($t1, $t2) = explode(' ', microtime());

    return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);

}

/**
 * 检测版本信息
 */
function check($UPDATE_URL)
{
    die(curl_get(false, $UPDATE_URL, ''));
}

function update($UPDATE_URL)
{
    $json = curl_get(false, $UPDATE_URL, '');
    $arr = json_decode($json, true);
    $newVersion = $arr['data']['version'];
    $updateDbaseStatus ="";
    if($newVersion>=SYSTEM_VERSION){
      if(count($arr['data']['sql'][SYSTEM_VERSION])>0){
          //执行sql语句
          $sutatData =  SQL::exec($arr['data']['sql'][SYSTEM_VERSION]);

          if (count($sutatData['errorDate']) > 0) {
           //   die(OperateResult::out(false,"更新未完成,升级数据库失败！",null));
              $updateDbaseStatus = "!";
          }
      }
        $src =$arr['data']['download'][$newVersion].'?t='.getMillisecond();

        download($src,ROOT);
        file_unzip(ROOT. 'update.zip', ROOT);
       die(OperateResult::out(true,"更新成功".$updateDbaseStatus,null));
    }else{
        die(OperateResult::out(false,"版本号异常！",null));
    }
}


/**
 * 下载文件
 * @param $source
 * @param $savePath
 */
function download($source, $savePath)
{
    //  $source = "http://newsq.6yun.17dl.top/up.zip";

    $ch = curl_init();//初始化一个cURL会话

    curl_setopt($ch, CURLOPT_URL, $source);//抓取url

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//是否显示头信息

    curl_setopt($ch, CURLOPT_SSLVERSION, 3);//传递一个包含SSL版本的长参数

    $data = curl_exec($ch);// 执行一个cURL会话

    $error = curl_error($ch);//返回一条最近一次cURL操作明确的文本的错误信息。

    curl_close($ch);//关闭一个cURL会话并且释放所有资源

    // $destination = './update.zip';
    $destination = $savePath . 'update.zip';

    $file = fopen($destination, "w+");

    fputs($file, $data);//写入文件

    fclose($file);
}

/**
 * 解压文件
 * @param $source
 * @param $unPath
 */
function file_unzip($source, $unPath)
{
    $zip = new ZipArchive();
    //$zipfile = './dl.zip';
    $zipfile = $source;
    //保存在当前目录下
    //$toDir = './';
    $toDir = $unPath;
    if ($zip->open($zipfile) === true) {
        $rf = zip_open($zipfile);
        $i = 0;
        while ($fr = zip_read($rf)) {

            $fileInfo = $zip->statIndex($i, ZipArchive::FL_ENC_RAW);
            //转码 否则中文会出现乱码
            $fileName = @iconv('UTF-8', 'GBK', $fileInfo['name']);

            //如果是目录
            if ($fileInfo['crc'] == 0) {
                //新建目录
                $dir = $toDir . $fileName;
                if (!file_exists($dir)) {
                    mkdir($dir, 0777, true);
                }
            } else {
                //读取文件内容并写入
                $content = zip_entry_read($fr, zip_entry_filesize($fr));
                file_put_contents($toDir.$fileName, $content);
            }
            $i++;
        }
    }
    $zip->close();
    unlink($source);
}


/**
 * curl模拟get进行 http 或 https url请求(可选附带cookie)
 * @param bool $type 请求类型：true为https请求,false为http请求
 * @param string $url 请求地址
 * @param string $cookie cookie字符串
 * @return    string    返回字符串
 */
function curl_get($type, $url, $cookie)
{//type与url为必传、若无cookie则传空字符串

    if (empty($url)) {
        return false;
    }

    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    if ($type) {  //判断请求协议http或https
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
    }
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    if (!empty($cookie)) curl_setopt($ch, CURLOPT_COOKIE, $cookie);  //设置cookie
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}
